package Sort;

import java.util.ArrayDeque;
import java.util.Deque;

public class QuickSortNor {
    /**
     * 快速排序的非递归
     */
    public static void swap(int[] arr,int i,int j){
        int tem=arr[i];
        arr[i]=arr[j];
        arr[j]=tem;
    }
    //hoare法
    public static int partition1(int[] arr,int left,int right){
        int par=arr[left];
        int tmp=left;
        while (left<right){
            while (left<right&&arr[right]>=par){
                right--;
            }
            while (left<right&&arr[left]<=par){
                left++;
            }
            swap(arr,left,right);
        }
        swap(arr,left,tmp);
        return left;
    }
    //挖坑法
    public static int partition2(int[] arr,int left,int right){
        int tmp=arr[left];
        while (left<right){
            while (left<right&&arr[right]>=tmp){
                right--;
            }
            arr[left]=arr[right];
            while (left<right&&arr[left]<=tmp){
                left++;
            }
            arr[right]=arr[left];
        }
        arr[right]=tmp;
        return right;
    }
    //前后指针法
    public static int partition3(int[] arr,int left,int right){
        int prev=left;
        int cur=left+1;
        while (cur<=right){
            if(arr[cur]<arr[left]&&arr[++prev]!=arr[cur]){
                swap(arr,prev,cur);
            }
            cur++;
        }
        swap(arr,prev,left);
        return prev;
    }
    public static void quickSortNor(int[] arr,int start,int end){
        Deque<Integer> stack=new ArrayDeque<>();
        int pivot=partition2(arr,start,end);
        if(pivot>start+1){
            stack.push(start);
            stack.push(pivot-1);
        }
        if (pivot<end-1){
            stack.push(pivot+1);
            stack.push(end);
        }
        while (!stack.isEmpty()){
            end=stack.pop();
            start=stack.pop();
            pivot=partition2(arr,start,end);
            if(pivot>start+1){
                stack.push(start);
                stack.push(pivot-1);
            }
            if (pivot<end-1){
                stack.push(pivot+1);
                stack.push(end);
            }
        }
    }

    public static void main(String[] args) {
        int[] array={5,1,9,4,3};
        quickSortNor(array,0,array.length-1);
        for (int i = 0; i <array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }
}
